#!/usr/bin/perl
# first call
# header("Content-Type: application/octet-stream\r\n\r\n") included.
require 'ChopSet.ph';

use Math::BigInt;

$|=1;
sysread(STDIN, $problem, $ENV{CONTENT_LENGTH});
unless($problem =~ m/(.+)\n(.+)\n(.+)/){
	print(" data format error: $problem");
	&endCall();
	exit(0);
}
$target = $1;
$start = $2;
$end  = $3;

# 33('!') to 126('~')
$startChar = 33;
$endChar = 126;

$nowInt = &str2int($start);
$endInt = &str2int($end);

# create "teruak", "terua", "teru", ...
$tmpTarget = $target;
while(length($tmpTarget) > 0){
	$tmpTarget = substr($tmpTarget, 0, length($tmpTarget) - 1);
	push(@subTargetsArray, $tmpTarget);
	$subTargets{$tmpTarget} = qr/$tmpTarget/;
}
$targetQr = qr/$target/;

print(" searching: $start $end\n");
$SIG{'USR1'} = sigUser1Handler;
while($nowInt <= $endInt){
	$targetString = &int2str($nowInt);
	$result = &trip($targetString);
	if($result =~ $targetQr){
		print("$targetString\t$target\t1\n");
		&printNowStatus();
		print(" normal exit.\n");
		&endCall();
		exit(0);
	}
	foreach $qr (@subTargetsArray){
		if($result =~ $subTargets{$qr}){
			$subTargetResult{$qr} = $targetString;
			$subTargetNum{$qr}++;
			last;
		}
	}
	$nowInt->badd(1);
}
&printNowStatus();
print(" not found.\n");

# last call.
&endCall();

sub sigUser1Handler{
	&printNowStatus();
	print(" killed.\n");
	&endCall();
	exit(0);
}

sub printNowStatus{
	my($subTarget);
	foreach $subTarget (@subTargetsArray){
		if(defined($subTargetResult{$subTarget})){
			print($subTargetResult{$subTarget}, "\t", $subTarget, "\t", $subTargetNum{$subTarget}, "\n");
		}
	}
}

sub trip($) {
	my $seed = shift;
	my $salt = substr($seed, 1, 2);
	my($precision) = 10;

	$salt =~ tr/\x3A-\x40\x5B-\x60/A-Ga-f/;
	$salt =~ s/[^\.\/0-9A-Za-z]/./g;

	return(substr(crypt($seed, $salt), -$precision));
}

sub str2int{
	my($str) = @_;
	@chars = unpack("C8", $str);
	my($startChar) = 33;
	my($endChar) = 126;
	my($char, $num);
	$num = Math::BigInt->new(0);
	foreach $char (@chars){
		$num *= ($endChar - $startChar);
		$num += $char - $startChar;
	}
	return $num;
}

sub int2str{
	my($bigInt) = @_;
	$bigInt = $bigInt->as_int();
	my(@chars);
	my($startChar) = 33;
	my($endChar) = 126;
	while($bigInt > 0){
		my($quo, $rem) = $bigInt->bdiv($endChar - $startChar);
		push(@chars, pack("C", $rem + $startChar));
		$bigInt = $quo;
	}
	join('', reverse(@chars));
}
